import {
  Controller,
  Post,
  Provide,
  Put,
  Get,
  Body,
  Inject,
  Param,
  Del,
  Query,
} from '@midwayjs/core';
import { MenuDTO } from '../dto/menu';
import { MenuService } from '../service/menu';
import { RuleType, Valid } from '@midwayjs/validate';
import { R } from '../../../common/base.error.util';
import { FindOptionsWhere } from 'typeorm';
import { BaseSysMenu } from '../entity/menu';

@Provide()
@Controller('/menu', { description: '菜单管理' })
export class MenuController {
  
  @Inject()
  menuService: MenuService;

  @Post('/', { description: '创建' })
  async create(@Body() data: MenuDTO) {
    return await this.menuService.create(data.toEntity());
  }

  @Put('/', { description: '编辑' })
  async edit(@Body() data: MenuDTO) {
    const entity = await this.menuService.getModel().findOneBy({ id: data.id });
    Object.assign(entity, data);
    return await this.menuService.edit(entity);
  }

  @Del('/:id', { description: '删除' })
  async remove(
    @Valid(RuleType.number().required().error(R.error('id不能为空')))
    @Param('id')
    id: number
  ) {
    const item = await this.menuService.getById(id);
    await this.menuService.remove(item);
  }

  @Get('/:id', { description: '根据id查询' })
  async getById(@Param('id') id: string) {
    return await this.menuService.getById(id);
  }
  
  @Get('/page', { description: '分页查询' })
  async page(
    @Query('page') page: number,
    @Query('size') size: number
  ) {
    const query: FindOptionsWhere<BaseSysMenu> = {};
    return await this.menuService.page(page, size, query);
  }
}
